﻿using shop.Bll;
using shop.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using unvell.ReoGrid;
using CommonTools;
using CommonTools.Controls;
using Flurl.Http;
using shop.job;

namespace shop.cost
{
    public partial class QueryTradeItemForm : DockContent
    {

        shop.Bll.cost.tradeItemBll _bll = new Bll.cost.tradeItemBll ();



        public QueryTradeItemForm()
        {
            InitializeComponent();

            this.box_begin.Value = DateTime.Today.AddDays(-10);
            this.box_end.Value = DateTime.Today;
        }

        private void btn_Query_Click(object sender, EventArgs e)
        {
            turnPageBox1_PageChanged(1, turnPageBox1.PageSize);
        }


        private void turnPageBox1_PageChanged(int pageNo, int pageSize)
        {
            var begin = box_begin.Value.Value.Date;
            var end = box_end.Value.Value.Date.LastTimeOfDay();

            var pr = new tradeItem()
            {
                shop_name = box_shop_name.Text.Trim(),
                logistics_no = box_logistics_no.Text.Trim(),
                trade_no = box_trade_no.Text.Trim(),
                warehouse = box_stock.Text.Trim(),
                goods_name = box_goods_name.Text.Trim(),
                spec_no = box_spec_no.Text.Trim(),
                src_tids= box_src_tids.Text.Trim(),
                Operator = box_Operator.Text.Trim(),
                platform_goods_id = box_platform_goods_id.Text.Trim(),
            };

            //if ((end - begin).TotalDays > 30)
            //{
            //    MessageBox.Show("日期范围不能超过30天", Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
            //    return;
            //}

            var res = WaitUI.Run(async () => await _bll.Query(begin, end, pr, pageNo, pageSize ));

            if (res.IsOk)
            {
                new GridDataBuilder(this.grid1)
                    .UseData(res.Data)
                    .AutoCreateColumns()
                    .UseFilter()
                    .SetReadOnly(true)
                    .End();

                if (pageNo == 1)
                {
                    this.turnPageBox1.Reset(res.Rows);
                }

                MessageTip.ShowOk(this, "查询完成");
            }
            else
            {
                MessageBox.Show(res.Message, Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private readonly Lazy<IFlurlClient> _client = new Lazy<IFlurlClient>(() => myApp.GetClient());

        /// <summary> 查询成本 </summary>
        private async void btn_queryCost_Click(object sender, EventArgs e)
        {
            var begin = box_begin.Value.Value.Date;
            var end = box_end.Value.Value.Date.LastTimeOfDay();

            var pr = new tradeItemQueryDto()
            {
                shop_name = box_shop_name.Text.Trim(),
                logistics_no = box_logistics_no.Text.Trim(),
                trade_no = box_trade_no.Text.Trim(),
                warehouse = box_stock.Text.Trim(),
                goods_name = box_goods_name.Text.Trim(),
                spec_no = box_spec_no.Text.Trim(),
                src_tids = box_src_tids.Text.Trim(),
                begin= begin,
                end= end,
                Opertaor= box_Operator.Text.Trim(),
                platform_goods_id = box_platform_goods_id.Text.Trim(),

            };

#if DEBUG
            var res = await _bll.QueryCost(pr);

#else
            //var res = await WaitUI.RunAsync(async () => await _bll.QueryCost( pr));

            var res = await WaitUI.RunAsync(async () =>
            {
                try
                {
                    var res1 = await _client.Value.Request("CostReport/QueryCostList")
                        .PostJsonAsync(pr)
                        .ReceiveJson<List<CostModel>>();

                    return res1;
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                }

            });
#endif


            new GridDataBuilder(this.grid1)
                .UseData(ToDisplayList( res))
                //.UseColumnTranslate()
                .UseFilter()
                .AutoCreateColumns()
                .DoActionAfter((sh, data) =>
                {
                    var cl =sh.GetColumnHeader(nameof(CostModel.OtherCost))?.Index;
                    if(cl != null)
                    {
                        sh.SetCellData(0, cl ?? 0, "提退款+补件+退款成功的利润（销售额的0.0336）");
                        sh.SetColumnsWidth(cl ?? 0, 1, 200);
                    }
                    sh.AutoFitRowHeight(0);
                })
                .End();

        }

        private async void btn_export_Click(object sender, EventArgs e)
        {
            if(this.progressBar1.Visible)
            {
                MessageBox.Show("有任务正在执行, 请等待!", Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            var begin = box_begin.Value.Value.Date;
            var end = box_end.Value.Value.Date.LastTimeOfDay();
            this.lab_work.Text = "";

            var pr = new tradeItemQueryDto()
            {
                shop_name = box_shop_name.Text.Trim(),
                logistics_no = box_logistics_no.Text.Trim(),
                trade_no = box_trade_no.Text.Trim(),
                warehouse = box_stock.Text.Trim(),
                goods_name = box_goods_name.Text.Trim(),
                spec_no = box_spec_no.Text.Trim(),
                src_tids = box_src_tids.Text.Trim(),
                begin= begin,
                end= end,
                Opertaor= box_Operator.Text.Trim(),
                platform_goods_id = box_platform_goods_id.Text.Trim(),

            };

            this.progressBar1.Visible = true;

            try
            {
                var time = DateTime.Now;

                //var res = Task.Run(async () => await _bll.QueryCost(begin, end, pr));
                //var res = await Task.Run(() => _bll.QueryCost(begin, end, pr));

                var res = await WaitUI.RunAsync(async () =>
                {
                    try
                    {
                        return (await _client.Value.Request("CostReport/QueryCostList")
                           .PostJsonAsync(pr)
                           .ReceiveJson<List<CostModel>>())
                           .Select(a => new
                           {
                               a.consign_time,
                               a.trade_no,
                               a.shop_name,
                               a.warehouse,
                               a.fenxiao,
                               a.src_tids,
                               a.trade_type,
                               a.receiver_district,
                               a.receiver_prov,
                               a.logistics_name,
                               a.logiAcct,
                               a.logistics_no,
                               a.cs_remark,
                               a.cs_flag,
                               a.spec_no,
                               a.goods_no,
                               a.goods_name,
                               a.spec_name,
                               a.api_goods_name,
                               a.api_spec_name,
                               a.platform_goods_id,
                               a.platform_spec_id,
                               a.suite_no,
                               //a.isAgent,
                               IsAgent = a.isAgent ? "是" : "否",
                               IsMult = a.IsMult ? "是" : "否",
                               //a.IsMult,
                               a.num,
                               a.actual_num,
                               a.paid,
                               a.goodsPrice,
                               a.CostAmount,
                               a.calc_post_cost,
                               a.DaifaAdd,
                               a.fandian,
                               a.shuadan,
                               a.OtherCost,
                               a.Profit,
                               a.ProfitRatio,
                               a.remark,
                               a.calc_num,
                               a.Operator,
                           }).ToList();
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                    finally
                    {
                    }

                });


                var span = DateTime.Now - time;

                //var res = await WaitUI.RunAsync(async () => await _bll.QueryCost(begin, end, pr));
                this.lab_work.Text = "任务用时 "+ span.ToString();
                var dict = new Dictionary<string, string>()
                {
                    { "consign_time",  "发货时间" },
                        { "trade_no",  "订单编号" },
                        { "shop_name",  "店铺名称" },
                        { "warehouse",  "仓库" },
                        { "fenxiao",  "分销商" },
                        { "src_tids",  "原始单号" },
                        { "trade_type",  "订单类型" },
                        { "receiver_district",  "收件人地区" },
                        { "receiver_prov",  "收件人省份" },
                        { "logistics_name",  "物流公司名称" },
                        { "logiAcct",  "快递老板" },
                        { "logistics_no",  "物流单号" },
                        { "cs_remark",  "客服备注" },
                        { "cs_flag",  "客服标旗" },
                        { "spec_no",  "商家编码" },
                        { "goods_no",  "货品编号" },
                        { "goods_name",  "货品名称" },
                        { "spec_name",  "规格名称" },
                        { "api_goods_name",  "平台货品名称" },
                        { "api_spec_name",  "平台规格名称" },
                        { "platform_goods_id",  "平台货品ID" },
                        { "platform_spec_id",  "平台规格ID" },
                        { "suite_no",  "来源组合装编码" },
                        { "IsAgent",  "是否代发 "},
                        { "IsMult",  "是否多把" },
                        { "num",  "下单数量" },
                        { "actual_num",  "实发数量" },
                        { "paid",  "订单支付金额" },
                        { "goodsPrice",  "成本" },
                        { "CostAmount",  "成本金额" },
                        { "calc_post_cost",  "运费" },
                        { "DaifaAdd",  "代发加收" },
                        { "fandian",  "返点" },
                        { "shuadan",  "刷单手续费" },
                        { "OtherCost",  "提退款+补件+退款成功的利润（销售额的0.0336）" },
                        { "Profit",  "利润" },
                        { "ProfitRatio",  "利润占比" },
                        { "remark",  "备注" },
                        { "calc_num",  "计算数量" },
                        { "Operator",  "运营负责人" },
                };

                new ExcelExporter()
                    .NewSheet("成本明细")
                    //.AddList(ToDisplayList( res))
                    .AddColumns(dict)
                    .AddList(res)
                    .SetBoolText("是","否")
                    .EndThenOpen(null);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            { 
                this.progressBar1.Visible = false; 
            }
          
        }

        private async void btn_findError_Click(object sender, EventArgs e)
        {
            var list = await WaitUI.RunAsync(async () => await _bll.FindError());

            new GridDataBuilder(this.grid1)
                .AutoCreateColumns()
                .UseFilter()
                .UseData(list)
                .End();
        }

        private async void btn_export2_Click(object sender, EventArgs e)
        {

            var begin = box_begin.Value.Value.Date;
            var end = box_end.Value.Value.Date.LastTimeOfDay();

            var pr = new tradeItemQueryDto()
            {
                shop_name = box_shop_name.Text.Trim(),
                logistics_no = box_logistics_no.Text.Trim(),
                trade_no = box_trade_no.Text.Trim(),
                warehouse = box_stock.Text.Trim(),
                goods_name = box_goods_name.Text.Trim(),
                spec_no = box_spec_no.Text.Trim(),
                src_tids = box_src_tids.Text.Trim(),
                begin = begin,
                end = end,
                FUser = UserBll.CurrentUser.Name,
                UserId = UserBll.CurrentUser.DocID.ToString(),
                Opertaor = box_Operator.Text.Trim(),
                platform_goods_id = box_platform_goods_id.Text.Trim(),

            };


            try
            {
                var res = await _client.Value.Request("CostReport/QueryCostRpt")
                    .PostJsonAsync(pr);

                MessageBox.Show("任务已创建", Properties.Resources.systemInformation, MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
            }
        }


        private IEnumerable<dynamic> ToDisplayList(IEnumerable<CostModel> list)
        {
            return list.Select(a => new
            {
                发货时间 = a.consign_time,
                订单编号 = a.trade_no,
                店铺名称 = a.shop_name,
                仓库 = a.warehouse,
                分销商 = a.fenxiao,
                原始单号 = a.src_tids,
                订单类型 = a.trade_type,
                收件人地区 = a.receiver_district,
                收件人省份 = a.receiver_prov,
                物流公司名称 = a.logistics_name,
                快递老板 = a.logiAcct,
                物流单号 = a.logistics_no,
                客服备注 = a.cs_remark,
                客服标旗 = a.cs_flag,
                商家编码 = a.spec_no,
                货品编号 = a.goods_no,
                货品名称 = a.goods_name,
                规格名称 = a.spec_name,
                平台货品名称 = a.api_goods_name,
                平台规格名称 = a.api_spec_name,

                平台货品ID = a.platform_goods_id,
                平台规格ID = a.platform_spec_id,
                来源组合装编码 = a.suite_no,
                是否代发 = a.isAgent ? "是" : "否",
                是否多把 = a.IsMult ? "是" : "否",
                下单数量 = a.num,
                实发数量 = a.actual_num,
                订单支付金额 = a.paid,
                成本 = a.goodsPrice,
                成本金额 = a.CostAmount,
                运费 = a.calc_post_cost,
                代发加收 = a.DaifaAdd,
                返点 = a.fandian,
                刷单手续费 = a.shuadan,
                a.OtherCost,
                利润 = a.Profit,
                利润占比 = a.ProfitRatio,
                退款编号= a.RefundNo,
                退款金额= a.RefundAmount,
                退款后支付金额= a.PayAmountRefund,
                退款后成本金额= a.CostAmountRefund,
                备注 = a.remark,
                计算数量 = a.calc_num,
                运营负责人 = a.Operator,
            }).ToList();

        }

        private void btn_backgroundJob_Click(object sender, EventArgs e)
        {
            myApp.OpenJobsForm();
        }
    }
}
